﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Linq;
using WEI_Share.Helpers;

namespace WEI_Share
{
	/// <summary>
	/// Interaction logic for Main.xaml
    /// http://msdn.microsoft.com/en-us/library/ms731177.aspx
    /// http://msdn.microsoft.com/en-us/library/ms730059.aspx
    /// http://msdn.microsoft.com/en-us/library/ms751505.aspx
	/// </summary>
    /// <![CDATA[
    /// svcutil.exe /n:http://Microsoft.ServiceModel.Samples,Microsoft.ServiceModel.Samples http://weisharetest.cloudapp.net:8080/WindowsExperienceService.svc?wsdl /async /tcv:Version35
    /// ]]>
	public partial class Main : Window
	{
        /// <summary>
        /// Progress indicator window...used for service posting
        /// </summary>
        ProgressIndicator progressWindow = null;

        /// <summary>
        /// Holds the object used for the posting of data to WEI Share
        /// </summary>
        WEIShareWCFRole.BusinessEntities.WindowsAssessment currentAssessment = null;

        /// <summary>
        /// The wcf service reference member
        /// </summary>
        WindowsExperienceServiceClient experienceClient = null;


		public Main()
		{
			InitializeComponent();

			PerformVersionCheck();

			//Setup the button events			
			uxLoadSite.MouseLeftButtonUp +=new System.Windows.Input.MouseButtonEventHandler(uxLoadSite_MouseLeftButtonUp);
			uxSubmitInfo.MouseLeftButtonUp +=new System.Windows.Input.MouseButtonEventHandler(uxSubmitInfo_MouseLeftButtonUp);
			uxRunWinSAT.Click += new RoutedEventHandler(uxRunWinSAT_Click);
			uxSubmitToFacebook.MouseLeftButtonUp +=new System.Windows.Input.MouseButtonEventHandler(uxSubmitToFacebook_MouseLeftButtonUp);

			uxMain.ContentRendered += new EventHandler(uxMain_ContentRendered);

		}


		#region Event Handlers - Window
		/// <summary>
		/// Handles the main event equivalent to winfows form .shown
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		void uxMain_ContentRendered(object sender, EventArgs e)
		{
			CheckForWinSatFile();
		}
		#endregion


		#region Event Handlers - Buttons

		/// <summary>
		/// Handles the launch website button
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void uxLoadSite_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start(Helpers.Globals.Website);
            }
            catch
            {
                MessageBox.Show("Unable to launch " + Environment.NewLine + Helpers.Globals.Website);
            }
        }


		/// <summary>
		/// Handles the submnit info button click
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void uxSubmitInfo_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
			if (!string.IsNullOrEmpty(Helpers.Globals.WinSatFileName))
			{
				SetupWinSatSubmittal();
			}
			else
				MessageBox.Show("No valid Windows Experience Index file found.");
        }


		/// <summary>
		/// Used to launch the WinSAT executable
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void uxRunWinSAT_Click(object sender, RoutedEventArgs e)
		{
			CheckForWinSatFile(true);
		}


		/// <summary>
		/// Handles the facebook submittal post
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void uxSubmitToFacebook_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
        	FaceBookWallPost();
        }
		#endregion


		#region PerformVersionCheck()
		/// <summary>
		/// Handles the version checking
		/// </summary>
		void PerformVersionCheck()
		{
			bool skipVersionCheck = false;

			if (App.Current.Properties.Contains("SkipVersionCheck"))
				skipVersionCheck = (bool)App.Current.Properties["SkipVersionCheck"];

			//check to see if it is a valid operating system to run this on
			if ((!skipVersionCheck) && (!Helpers.Utilities.IsValidWindowsVersion()))
			{
				this.WindowState = WindowState.Minimized;
				MessageBox.Show("This application requires Windows 7 to run.", "Load Error");
				Application.Current.Shutdown();
			}
		}
		#endregion


		#region WEI Inforation Submittal Methods
		/// <summary>
		/// Setups up the wcf service call and submits the data to the service
		/// </summary>
		private void SetupWinSatSubmittal()
		{
			//retrieve specific system info
			XElement baseItem = Helpers.Globals.WinSatXmlDocument;
			if (baseItem != null)
			{
                progressWindow = new ProgressIndicator();
			    progressWindow.Show();
                currentAssessment = new WEIShareWCFRole.BusinessEntities.WindowsAssessment();
                Globals.WinsatSubmittalPosition currentPosition = Globals.WinsatSubmittalPosition.NotStarted;

				try
				{
					List<XElement> itemList = null;
                    List<WMIItem> response = null;
					XElement specificItem = null;

					//scores
                    currentPosition = Globals.WinsatSubmittalPosition.SystemScores;
                    itemList = baseItem.Element("WinSPR").Descendants().ToList(); ;
                    if ((itemList != null) && (itemList.Count > 0))
                    {
                        currentAssessment.CpuScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "CpuScore"));
                        currentAssessment.CpuSubAggScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "CPUSubAggScore"));
                        currentAssessment.MemoryScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "MemoryScore"));
                        currentAssessment.GraphicsScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "GraphicsScore"));
                        currentAssessment.GamingScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "GamingScore"));
                        currentAssessment.VideoEncodeScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "VideoEncodeScore"));
                        currentAssessment.DiskScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "DiskScore"));
                        currentAssessment.SystemScore = Helpers.Conversion.ToDecimalOrNull(Helpers.Utilities.GetElementValue(itemList, "SystemScore"));
                    }					


                    currentPosition = Globals.WinsatSubmittalPosition.OS;
                    itemList = baseItem.Element("SystemConfig").Element("OSVersion").Descendants().ToList();
                    if ((itemList != null) && (itemList.Count > 0))
                    {
                        currentAssessment.OSVersionBuild = Helpers.Utilities.GetElementValue(itemList, "Build");
                        currentAssessment.OSVersionProductType = Helpers.Utilities.GetElementValue(itemList, "ProductType");
                        currentAssessment.OSVersionProductName = Helpers.Utilities.GetElementValue(itemList, "ProductName");
                    }


                    currentPosition = Globals.WinsatSubmittalPosition.Platform;
                    itemList = baseItem.Element("SystemConfig").Element("Platform").Descendants().ToList();
                    if ((itemList != null) && (itemList.Count > 0))
                    {
                        currentAssessment.PlatformIsMobile = Helpers.Conversion.ToBoolOrNull(Helpers.Utilities.GetElementValue(itemList, "IsMobile"));
                        currentAssessment.PlatformRoleDesc = Helpers.Utilities.GetElementAttributeValue(itemList, "PlatformRole", "desc");
                        currentAssessment.PlatformRole = Helpers.Utilities.GetElementValue(itemList, "PlatformRole");
                    }


                    currentPosition = Globals.WinsatSubmittalPosition.Processor;
                    itemList = baseItem.Element("SystemConfig").Element("Processor").Element("Instance").Descendants().ToList();
                    if ((itemList != null) && (itemList.Count > 0))
                    {
                        currentAssessment.ProcessorName = Helpers.Utilities.GetElementValue(itemList, "ProcessorName");
                        currentAssessment.ProcessorFrequency = Helpers.Conversion.ToLongOrNull(Helpers.Utilities.GetElementValue(itemList, "TSCFrequency"));
                        currentAssessment.ProcessorNumProcs = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "NumProcs"));
                        currentAssessment.ProcessorNumCores = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "NumCores"));
                        currentAssessment.ProcessorNumCPUs = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "NumCPUs"));
                        currentAssessment.ProcessorNumCPUsPerCore = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "NumCPUsPerCore"));
                        currentAssessment.ProcessorNumCoresPerProcessor = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "NumCoresPerProcessor"));
                        currentAssessment.ProcessorX64Capable = Helpers.Conversion.ToBoolOrNull(Helpers.Utilities.GetElementValue(itemList, "X64Capable"));
                        currentAssessment.ProcessorX64Running = Helpers.Conversion.ToBoolOrNull(Helpers.Utilities.GetElementValue(itemList, "X64Running"));
                    }

                    currentPosition = Globals.WinsatSubmittalPosition.ProcessorL1Cache;
                    specificItem = baseItem.Element("SystemConfig").Element("Processor").Element("Instance").Element("L1Cache").Element("Size");
                    if (specificItem != null)
                        currentAssessment.ProcessorL1CacheSize = Helpers.Conversion.ToIntOrNull(specificItem.Value);

                    currentPosition = Globals.WinsatSubmittalPosition.ProcessorL2Cache;
                    specificItem = baseItem.Element("SystemConfig").Element("Processor").Element("Instance").Element("L2Cache").Element("Size");
                    if (specificItem != null)
                        currentAssessment.ProcessorL2CacheSize = Helpers.Conversion.ToIntOrNull(specificItem.Value);
                    

                    currentPosition = Globals.WinsatSubmittalPosition.PhysicalMemory;
                    itemList = baseItem.Element("SystemConfig").Element("Memory").Element("TotalPhysical").Descendants().ToList();
                    if ((itemList != null) && (itemList.Count > 0))
                    {
                        currentAssessment.MemoryPhysicalSize = Helpers.Utilities.GetElementValue(itemList, "Size");
                        currentAssessment.MemoryPhysicalSizeBytes = Helpers.Conversion.ToLongOrNull(Helpers.Utilities.GetElementValue(itemList, "Bytes"));
                    }

                    itemList = baseItem.Element("SystemConfig").Element("Memory").Element("AvailablePhysical").Descendants().ToList();
                    if ((itemList != null) && (itemList.Count > 0))
                    {
                        currentAssessment.MemoryAvailablePhysicalSize = Helpers.Utilities.GetElementValue(itemList, "Size");
                        currentAssessment.MemoryAvailablePhysicalSizeBytes = Helpers.Conversion.ToLongOrNull(Helpers.Utilities.GetElementValue(itemList, "Bytes"));
                    }
                    

                    currentPosition = Globals.WinsatSubmittalPosition.Monitor;
                    specificItem = baseItem.Element("SystemConfig").Element("Monitors").Element("Count");
                    if (specificItem != null)
                        currentAssessment.MonitorsCount = Helpers.Conversion.ToIntOrNull(specificItem.Value);

                    var monitorItems = from currentMonitor in baseItem.Element("SystemConfig").Element("Monitors").Elements("Monitor")
                                       where currentMonitor.Attribute("primary").Value == "1"
                                       select currentMonitor;
                    if (monitorItems != null)
                    {
                        itemList = monitorItems.Descendants().ToList();
                        if ((itemList != null) && (itemList.Count > 0))
                        {
                            currentAssessment.MonitorWidth = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "Width"));
                            currentAssessment.MonitorHeight = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "Height"));
                            currentAssessment.MonitorTotalPixels = Helpers.Conversion.ToIntOrNull(Helpers.Utilities.GetElementValue(itemList, "TotalMonitorPixels"));
                        }
                    }
                    

                    currentPosition = Globals.WinsatSubmittalPosition.Graphics;
                    itemList = baseItem.Element("SystemConfig").Element("Graphics").Descendants().ToList();
                    if ((itemList != null) && (itemList.Count > 0))
                    {
                        currentAssessment.GraphicsAdapterDescription = Helpers.Utilities.GetElementValue(itemList, "AdapterDescription");
                        currentAssessment.GraphicsAdapterManufacturer = Helpers.Utilities.GetElementValue(itemList, "AdapterManufacturer");
                        currentAssessment.GraphicsDedicatedVideoMemory = Helpers.Conversion.ToLongOrNull(Helpers.Utilities.GetElementValue(itemList, "DedicatedVideoMemory"));
                        currentAssessment.GraphicsDedicatedSystemMemory = Helpers.Conversion.ToLongOrNull(Helpers.Utilities.GetElementValue(itemList, "DedicatedSystemMemory"));
                        currentAssessment.GraphicsSharedSystemMemory = Helpers.Conversion.ToLongOrNull(Helpers.Utilities.GetElementValue(itemList, "SharedSystemMemory"));
                        currentAssessment.GraphicsSupports32BitsPerPixel = Helpers.Conversion.ToBoolOrNull(Helpers.Utilities.GetElementValue(itemList, "Suports32BitsPerPixel"));
                        currentAssessment.GraphicsDriverVersion = Helpers.Utilities.GetElementAttributeValue(itemList, "DriverVersion", "Friendly");
                    }


                    currentPosition = Globals.WinsatSubmittalPosition.HardDiskSpeed;
                    //disk read/write speed
                    specificItem = baseItem.Element("Metrics").Element("DiskMetrics").Element("AvgThroughput");
                    if (specificItem != null)
                        currentAssessment.DiskSpeed = Helpers.Conversion.ToDecimalOrNull(specificItem.Value);


                    currentPosition = Globals.WinsatSubmittalPosition.PrimaryHardDiskFreeSpace;
                    //hard drive
                    long? diskSize = null;
                    var currentItem = (from item in baseItem.Element("SystemConfig").Element("Disk").Elements("SystemDisk")
                                       select item);

                    if (currentItem != null)
                    {
                        specificItem = currentItem.FirstOrDefault();
                        if (specificItem != null)
                        {
                            diskSize = Helpers.Conversion.ToLongOrNull(Helpers.Utilities.GetElementValue(specificItem.Descendants().ToList(), "Size"));

                            currentAssessment.DiskSize = diskSize;

                            if ((diskSize.HasValue) && (diskSize.Value > 0))
                            {   
                                string diskDeviceID = Helpers.Utilities.GetElementAttributeValue(specificItem, "id").Replace("\\", @"\");

                                currentPosition = Globals.WinsatSubmittalPosition.SystemPrimaryHardDiskFreeSpace;

                                List<Helpers.DriveData> driveResponse = Helpers.WMISystemInfo.GetPrimaryDriveInfo(diskDeviceID);
                                if ((driveResponse != null) && (driveResponse.Count > 0))
                                {
                                    long totalUsed = 0;
                                    foreach (Helpers.DriveData current in driveResponse)
                                        totalUsed += (current.Size - current.Freespace);

                                    currentAssessment.DiskSizeAvailable = diskSize.Value - totalUsed;
                                }
                            }
                        }
                    }

                    currentPosition = Globals.WinsatSubmittalPosition.TouchPoints;
					//get touches
					currentAssessment.TouchPointCount = Helpers.WindowsAPI.GetSystemMetrics(Helpers.WindowsAPI.SystemMetric.SM_MAXIMUMTOUCHES);

                    

                    //Manufacturer
                    //Model
                    //SystemType
                    currentPosition = Globals.WinsatSubmittalPosition.SystemSystemInformation;
                    response = Helpers.WMISystemInfo.GetComputerSystemItems();
                    if ((response != null) && (response.Count > 0))
                    {
                        var item = response.Where(i => i.Key == "Manufacturer").FirstOrDefault();
                        if ((item != null) && (item.Value != null))
                            currentAssessment.SystemManufacturer = item.Value.ToString();

                        item = response.Where(i => i.Key == "Model").FirstOrDefault();
                        if ((item != null) && (item.Value != null))
                            currentAssessment.SystemModel = item.Value.ToString();

                        item = response.Where(i => i.Key == "SystemType").FirstOrDefault();
                        if ((item != null) && (item.Value != null))
                            currentAssessment.SystemType = item.Value.ToString();
                    }


                    //MemoryType
                    //MemorySpeed
                    currentPosition = Globals.WinsatSubmittalPosition.SystemPhysicalMemory;
                    response = Helpers.WMISystemInfo.GetPhysicalMemory();
                    if ((response != null) && (response.Count > 0))
                    {
                        var item = response.Where(i => i.Key == "MemoryType").FirstOrDefault();
                        if ((item != null) && (item.Value != null))
                            currentAssessment.MemoryTypeID = Helpers.Conversion.ToIntOrNull(item.Value.ToString());

                        item = null;
                        item = response.Where(i => i.Key == "Speed").FirstOrDefault();
                        if ((item != null) && (item.Value != null))
                            currentAssessment.MemorySpeed = Helpers.Conversion.ToIntOrNull(item.Value.ToString());
                    }


                    //macaddress
                    currentPosition = Globals.WinsatSubmittalPosition.SystemNetworkCard;
                    response = Helpers.WMISystemInfo.GetNetworkCardInfo();
                    if ((response != null) && (response.Count > 0))
                    {
                        var item = response.Where(i => i.Key == "MacAddress").FirstOrDefault();
                        if ((item != null) && (item.Value != null))
                            currentAssessment.MACAddress = item.Value.ToString();
                    }


					//call wcf service 
                    currentPosition = Globals.WinsatSubmittalPosition.WCFServiceInitial;

                    CustomBinding myBinding = new CustomBinding();
                    myBinding.Elements.Add(Helpers.Globals.CustomServiceBinding);
                    myBinding.Elements.Add(Helpers.Globals.CustomTransportBinding);
                    experienceClient = new WindowsExperienceServiceClient(myBinding, Helpers.Globals.CustomEndPoint);
                    
                    experienceClient.SubmitWindowsAssessmentCompleted += new EventHandler<SubmitWindowsAssessmentCompletedEventArgs>(experienceClient_SubmitWindowsAssessmentCompleted);
                    experienceClient.SubmitWindowsAssessmentAsync(currentAssessment, Helpers.Cryptor.Encrypt(String.Format(Properties.Resources.WEIServiceKey + "|{0}", Properties.Resources.WEIServiceVersion)));
				}
				catch(Exception ex)
				{
					MessageBox.Show(String.Format("Oops! An error has occurred. Exception Details:" + Environment.NewLine + Environment.NewLine + "{0}", Globals.GetWinsatSubmittalErrorMessage(currentPosition, ex)));
                    //reset all of the elements used for the service setup/communication
                    ResetServiceRelatedElements();
				}
			}
            else
                MessageBox.Show("No valid Windows Experience Index file specified for submittal.");
		}


        /// <summary>
        /// Handles the completion event when posting scores and other date to the service
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void experienceClient_SubmitWindowsAssessmentCompleted(object sender, SubmitWindowsAssessmentCompletedEventArgs e)
        {
            if ((!e.Cancelled) && (e.Error == null))
            {
                WEIShareWCFRole.BusinessEntities.Response serviceResponse = e.Result;

                if (serviceResponse.StatusCode == 100)
                    MessageBox.Show("Scores successfully posted.");
                else
                    MessageBox.Show(String.Format("Oops! An error has occurred. Exception Details: {0}", serviceResponse.StatusMessage));
            }
            else
            {
                if (e.Cancelled)
                    MessageBox.Show(String.Format("Oops! An error has occurred. Exception Details: {0}", "The service communication was cancelled."));
                else if (e.Error != null)
                    MessageBox.Show(String.Format("Oops! An error has occurred. Exception Details: {0}", e.Error.Message));
            }

            //reset all of the elements used for the service setup/communication
            ResetServiceRelatedElements();
        }

        /// <summary>
        /// Nulls out the items used such as progress window and global members
        /// </summary>
        void ResetServiceRelatedElements()
        {
            //empty out the service reference
            experienceClient = null;

            if (progressWindow != null)
                progressWindow.Close();

            //empty out the progress windowreference
            progressWindow = null;
        }
        
		#endregion


		#region DisplayScores
		/// <summary>
		/// Displays the retrieved scores on the screen otherwise defaults to 0
		/// </summary>
		private void DisplayScores()
		{
			XElement current = Helpers.Globals.WinSatXmlDocument;
			if (current != null)
			{
				List<XElement> itemList = current.Elements("WinSPR").Descendants().ToList(); ;
				if ((itemList != null) && (itemList.Count > 0))
				{
					uxProcessor.Content = Helpers.Utilities.GetElementValue(itemList, "CpuScore");
					uxMemory.Content = Helpers.Utilities.GetElementValue(itemList, "MemoryScore");
					uxGraphics.Content = Helpers.Utilities.GetElementValue(itemList, "GraphicsScore");
					uxGaming.Content = Helpers.Utilities.GetElementValue(itemList, "GamingScore");
					uxDisk.Content = Helpers.Utilities.GetElementValue(itemList, "DiskScore");
					uxOverall.Content = Helpers.Utilities.GetElementValue(itemList, "SystemScore");
				}
			}
			else
			{
				uxProcessor.Content = "0";
				uxMemory.Content = "0";
				uxGraphics.Content = "0";
				uxGaming.Content = "0";
				uxDisk.Content = "0";
				uxOverall.Content = "0";
			}
		}
		#endregion


		#region CheckForWinSatFile()
		/// <summary>
		/// Checks for the WinSAT file and inquires if a new one should be generated
		/// </summary>
		private void CheckForWinSatFile()
		{
			CheckForWinSatFile(false);
		}

		private void CheckForWinSatFile(bool askToRerunIfFound)
		{
			bool processScore = false;

			//if no valid file (within the last day), prompt to run the WinSat application
			if (!SetupWinSatFile())
			{
				//prompt to run the winsat
				MessageBoxResult result = MessageBox.Show
					(
						"There is no recent valid Experience Index score.  Do you want to run the Windows Experience Index Assessment Tool to generate a score?" + Environment.NewLine + Environment.NewLine + "This requires Administrator privileges to run.",
						"Generate Windows Site Assessment",
						MessageBoxButton.YesNo,
						MessageBoxImage.Question,
						MessageBoxResult.Yes
					);

				if (result == MessageBoxResult.Yes)
				{
					SetupAndRunWinSAT();
				}
			}
			else if (!askToRerunIfFound)
			{
				processScore = true;
			}
			else
			{
				//prompt to run the winsat anyways
				MessageBoxResult result = MessageBox.Show
					(
						"A recent valid Experience Index score was found.  Do you still want to run the Windows Experience Index Assessment Tool to generate a score?" + Environment.NewLine + Environment.NewLine + "This requires Administrator privileges to run.",
						"Generate Windows Site Assessment",
						MessageBoxButton.YesNo,
						MessageBoxImage.Question,
						MessageBoxResult.Yes
					);

				if (result == MessageBoxResult.Yes)
					SetupAndRunWinSAT();
				else
					processScore = true;
			}

			if(processScore)
				CheckForAndProcessScore();
		}
		#endregion


        #region SetupAndRunWinSAT
        /// <summary>
		/// Launches the dialog that handles launching WinSat and checking if it is running.
		/// </summary>
		private void SetupAndRunWinSAT()
		{
			WinSatProgress progressWindow = new WinSatProgress();
			bool? dialogResult = progressWindow.ShowDialog();
			if (dialogResult.HasValue && dialogResult.Value)
				CheckForAndProcessScore();
        }
        #endregion


        #region SetupWinSatFile()
        /// <summary>
		/// Gets the file to be used for the WinSAT scores posting and displays the date of the scoring
		/// </summary>
		/// <returns></returns>
		private bool SetupWinSatFile()
		{
			//reset the filename
			Helpers.Globals.WinSatFileName = null;

			System.IO.FileInfo specificFile = Helpers.Utilities.GetLatestWinSATFileInfo();
			if (specificFile != null)
			{
				//Parse off the date
				DateTime? fileDate = Helpers.Utilities.GetDateFromFileName(specificFile.Name);

				if ((fileDate.HasValue) && (fileDate.Value.AddDays(1) > DateTime.Now))
				{
					//Assign the "global" winsat filename to possibly be used
					Helpers.Globals.WinSatFileName = specificFile.FullName;

					uxLastIndexDate.Content = fileDate.Value.ToString("MMMM d, yyyy h:mmtt");

					//enabkle the buttons for posting
					uxSubmitInfo.IsEnabled = true;
					uxSubmitToFacebook.IsEnabled = true;

					return true;
				}
			}

			return false;
		}
		#endregion
		

		#region CheckForAndProcessScore
		/// <summary>
		/// Checks to see if the user wants tp process the score to the site
		/// </summary>
		private void CheckForAndProcessScore()
		{
			SetupWinSatFile();

			if (!string.IsNullOrEmpty(Helpers.Globals.WinSatFileName))
			{
				//Load the file
				Helpers.Utilities.LoadXmlData(Helpers.Globals.WinSatFileName);

				//display scores
				DisplayScores();

				//prompt for posting
				MessageBoxResult result = MessageBox.Show
					(
						"Would you like to post your scores to the website?",
						"Post Windows Site Assessment",
						MessageBoxButton.YesNo,
						MessageBoxImage.Question,
						MessageBoxResult.Yes
					);

				if (result == MessageBoxResult.Yes)
					SetupWinSatSubmittal();
			}
			else
			{
				MessageBox.Show("No valid Windows Experience Index file found.");
			}
		}
		#endregion


        #region FaceBookWallPost
        /// <summary>
        /// Performs login and permission authentication for facebook posting
        /// </summary>
        void FaceBookWallPost()
        {
            try
            {
                decimal? score = Helpers.Conversion.ToDecimalOrNull(uxOverall.Content.ToString());

                if (score.HasValue)
                {
                    Facebook.AttachmentHelper.attachment attach = new Facebook.AttachmentHelper.attachment();
                    attach.name = "WEI Share - My Score is " + score.ToString() + " – Rate Your Machine";
                    attach.href = Helpers.Globals.Website;
                    //attach.description = "test of this";
                    attach.caption = "Share your Windows Experience Index score, compare with Facebook friends, and find the best driver versions for your hardware";

                    Facebook.AttachmentHelper.attachment_media_image image = new Facebook.AttachmentHelper.attachment_media_image();
                    image.type = Facebook.AttachmentHelper.attachment_media_type.image;
                    image.href = Helpers.Globals.Website;


                    //images start at 01 (score 0.0)
                    score = (score * 10) + 1;

                    image.src = Helpers.Globals.FacebookScoreImageFolder + "wei__f" + Math.Truncate(score.Value).ToString().PadLeft(2, '0') + ".jpg";

                    attach.media = new List<Facebook.AttachmentHelper.attachment_media>();
                    attach.media.Add(image);

                    Facebook.API fbi = new Facebook.API(); // Create the API wrapper class and session

                    string postResult = fbi.PublishStream("", attach);
                }
                else
                    MessageBox.Show("Unable to setup scoring information for Facebook post.");

            }
            catch (Exception ex) // Catch any exception thrown durning the login (only a successful login results in no exception)
            {
                MessageBox.Show(ex.Message, "An error occurred attempting to connect and post to Facebook");
            }
        }

        #endregion




		
	}
}
